package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.time.format.DateTimeFormatter;
import java.util.List;

@Controller
public class TraditionalUserManagementController {

    @Autowired
    private UserService userService;

    // 使用传统的Spring MVC模式，返回视图名称
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/traditional-user-management")
    public String showUserManagementPage(Authentication authentication, Model model) {
        // 获取当前登录用户
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username);
        
        // 获取所有用户列表
        List<User> users = userService.findAll();
        
        // 添加数据到模型
        model.addAttribute("users", users);
        model.addAttribute("currentUserId", currentUser.getId());
        
        // 返回简化的Thymeleaf视图名称
        return "simple_user_management";
    }
    
    // 更新用户状态
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/traditional-user/update-status")
    public String updateUserStatus(@RequestParam("userId") Long userId, @RequestParam("status") Integer status) {
        userService.updateStatus(userId, status);
        return "redirect:/traditional-user-management";
    }
    
    // 删除用户
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/traditional-user/delete")
    public String deleteUser(@RequestParam("userId") Long userId, RedirectAttributes redirectAttributes) {
        userService.delete(userId);
        redirectAttributes.addFlashAttribute("message", "用户已成功删除");
        return "redirect:/traditional-user-management";
    }
}